package com.founder.barcode.bussiness.util;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.xerces.impl.dv.util.Base64;

import com.founder.barcode.bussiness.xml.XmlParserUtil;
import com.founder.barcode.common.util.Configuration;
import com.founder.barcode.common.util.HttpClientUtil;

public abstract class BaseService {
    
    protected static String BUSS_URL = Configuration.getInstance().getConfiguration("buss_url");
    
    protected static String ADMIN_URL = Configuration.getInstance().getConfiguration("admin_url");
    
    /**
     * base64加密
     * @throws Exception
     */
    protected void encodeBase64() {
        
    }
    
    protected String getXml(String uri) throws IOException {
        URL url = this.getClass().getResource(uri);
        String xml = FileUtils.readFileToString(new File(url.getPath()));
        return xml;
    }
    
    protected String getXml(String uri,Map<String,String> params) throws IOException {
        this.encodeBase64();
        String xml = this.getXml(uri);
        return replaceXml(xml, params);
    }
    
    protected String replaceXml(String xml,Map<String,String> params) {
        for(Entry<String,String> entry : params.entrySet()) {
            xml = StringUtils.replace(xml, "${" + entry.getKey() + "}", entry.getValue());
        }
        return xml;
    }
    
    protected String base64Encode(byte[] src) {
        return Base64.encode(src);
    }
    
    protected byte[] desEncode(byte[] src) {
        return DESUtil.encryptMode(DESUtil.keyBytes, src);
    }
    
    protected byte[] base64Decode(String src) {
        return Base64.decode(src);
    }
    
    protected byte[] desDecode(byte[] src) {
        return DESUtil.decryptMode(DESUtil.keyBytes, src);
    }
    
    protected String encode(byte[] src) {
        return this.base64Encode(this.desEncode(src));
    }
    
    protected String decode(String src) {
        return new String(this.desDecode(this.base64Decode(src)));
    }
    
    protected String sendRequest(String uri,String xml) throws Exception {
        String result = HttpClientUtil.postRequest(uri, xml);
        return result;
    }
    
    /**
     * 判断报文的Code是否与target相等
     * @param xml
     */
    protected String success(String xml,String target) {
        String code = XmlParserUtil.getXMLValue(xml, "Code");
        assertThat(target, is(code));
        return xml;
    }
    
    protected String success(String xml) {
        System.out.println("responseXMl == " + xml);
        this.success(xml,"1000");
        return xml;
    }
}
